<template>
<view class="container" v-if="myCardVoucherDetail">
  <view class="my_card_voucher_detail">
  <!-- {{myCardVoucherDetail.cardBanner&&myCardVoucherDetail.cardBanner!="undefined"?"background-image":"background"}}:{{myCardVoucherDetail.cardBanner&&myCardVoucherDetail.cardBanner!="undefined"?"url("+myCardVoucherDetail.cardBanner+")":myCardVoucherDetail.cardColor}} -->
    <view class="my_card_voucher_card" v-if="myCardVoucherDetail.cardVoucher.cardBanner&&myCardVoucherDetail.cardVoucher.cardBanner!='undefined'" :style="'background-image:url(' + myCardVoucherDetail.cardVoucher.cardBanner + ')'">
      <!-- <view class="ewmCode" v-if="myCardVoucherDetail.exhause==0&&myCardVoucherDetail.status==1" @click.stop="tolinkUrl" :data-link="'show_verification_code.html?code=' + myCardVoucherDetail.instanceCode + '&verifyScanType=1'">
        <image class="ewmImg" src="https://image1.sansancloud.com/xianhua/2019_1/4/15/2/28_123.jpg"></image>
      </view> -->
      <view class="share_block" v-if="loginUser.platformUser.id==myCardVoucherDetail.gainPlatformUserId&&myCardVoucherDetail.shareAble==1&&(myCardVoucherDetail.countPerInstance-myCardVoucherDetail.usedCount>0||myCardVoucherDetail.countPerInstance<0)">
          <image class="share_icon" src="https://image1.sansancloud.com/xianhua/2019_7/9/17/4/27_602.jpg?x-oss-process=style/preview_120" @click.stop="showShare" mode="aspectFit"></image>
      </view>
    </view>
    <view class="my_card_voucher_card" v-else :style="'background:' + myCardVoucherDetail.cardVoucher.cardColor">
        <view class="share_block" v-if="loginUser.platformUser.id==myCardVoucherDetail.gainPlatformUserId&&myCardVoucherDetail.shareAble==1&&(myCardVoucherDetail.countPerInstance-myCardVoucherDetail.usedCount>0)">
            <image class="share_icon" src="https://image1.sansancloud.com/xianhua/2019_7/9/17/4/27_602.jpg?x-oss-process=style/preview_120" @click.stop="showShare" mode="aspectFit"></image>
        </view>
      <view class="my_card_voucher_baseinfo">
        <image class="my_card_voucher_logo" :src="(myCardVoucherDetail.cardVoucher.cardImage?myCardVoucherDetail.cardVoucher.cardImage:'https://image1.sansancloud.com/xianhua/2018_12/21/17/44/1_472.jpg')"></image>
        <view class="my_card_voucher_name">
          <text class="my_card_voucher_platformname">{{loginUser.platformUser.belongMendianName}}</text>
          <text class="my_card_voucher_value">{{myCardVoucherDetail.cardName}}</text>
        </view>
      </view>
      <view class="my_card_voucher_limit_time">
        <text>有效期：</text>
        <text v-if="myCardVoucherDetail.validateType==1">永久有效</text>
        <text v-if="myCardVoucherDetail.validateType==3">{{myCardVoucherDetail.validateDatetimeEnd}}后失效</text>
        <text v-if="myCardVoucherDetail.validateType==2">{{myCardVoucherDetail.validateDatetimeEnd}}后失效</text>
      </view>
     <!-- <view class="ewmCode" v-if="myCardVoucherDetail.exhause==0&&myCardVoucherDetail.status==1" @click.stop="tolinkUrl" :data-link="'show_verification_code.html?code=' + myCardVoucherDetail.instanceCode + '&verifyScanType=1'">
        <image class="ewmImg" src="https://image1.sansancloud.com/xianhua/2019_1/4/15/2/28_123.jpg"></image>
      </view> -->
    </view>
    <!-- 卡券详情 -->
    <view class="extra_info" v-if="loginUser.platformUser.id==myCardVoucherDetail.gainPlatformUserId">
      <view class="extra_info_item">
        <text class="extra_info_title">剩余次数</text>
        <text class="extra_info_value" :style="'color:' + platformSetting.defaultColor" v-if="myCardVoucherDetail.countPerInstance==-1">无限次</text>
        <text class="extra_info_value" :style="'color:' + platformSetting.defaultColor" v-else>{{myCardVoucherDetail.countPerInstance-myCardVoucherDetail.usedCount}}</text>
      </view>
      <view class="extra_info_item">
        <text class="extra_info_title">已用次数</text>
        <text class="extra_info_value" :style="'color:' + platformSetting.defaultColor">{{myCardVoucherDetail.usedCount}}</text>
      </view>
    </view>
    <!-- 领取卡券 -->
    <view class="extra_info" v-else>
      <view class="extra_info_item">
        <text class="extra_info_title">剩余次数</text>
        <text class="extra_info_value" :style="'color:' + platformSetting.defaultColor">{{myCardVoucherDetail.shareCount-myCardVoucherDetail.shareGainCount}}</text>
      </view>
      <view class="extra_info_item">
        <text class="extra_info_title">已领次数</text>
        <text class="extra_info_value" :style="'color:' + platformSetting.defaultColor">{{myCardVoucherDetail.shareGainCount}}</text>
      </view>
    </view>
  </view>
  <view class="card_voucher_description">
    <view class="card_voucher_description_item">
      <text class="card_voucher_description_name">卡券说明</text>
      <text class="card_voucher_description_description">{{myCardVoucherDetail.cardVoucher.description}}</text>
    </view>
    <view class="card_voucher_description_item">
      <text class="card_voucher_description_name">有效期限</text>
      <text class="card_voucher_description_description" v-if="myCardVoucherDetail.validateType==1">永久有效</text>
      <text class="card_voucher_description_description" v-if="myCardVoucherDetail.validateType==3">{{myCardVoucherDetail.validateDatetimeEnd}}后失效</text>
      <text class="card_voucher_description_description" v-if="myCardVoucherDetail.validateType==2">{{myCardVoucherDetail.validateDatetimeEnd}}后失效</text>
    </view>
    <view class="card_voucher_description_item">
      <text class="card_voucher_description_name">核销编码</text>
      <text class="card_voucher_description_description">{{myCardVoucherDetail.instanceCode}}</text>
    </view>
    <block v-if="myCardVoucherDetail.shareAble>0">
        <view class="card_voucher_description_item">
          <text class="card_voucher_description_name">分享次数</text>
          <text class="card_voucher_description_description">{{myCardVoucherDetail.shareCount}}次</text>
        </view>
        <view class="card_voucher_description_item" :data-link="'share_get_records.html?cardVoucherInstanceId='+myCardVoucherDetail.id" @tap="tolinkUrl">
          <text class="card_voucher_description_name">领取次数</text>
          <text class="card_voucher_description_description">{{myCardVoucherDetail.shareGainCount}}次</text>
        </view>
    </block>
  </view>
  <view class="ewm_block" v-if="loginUser.platformUser.id==myCardVoucherDetail.gainPlatformUserId">
      <!-- <text class="ewm_title">核销码</text> -->
      <view class="ewm_img">
          <image :src="ewmCode" class="ewm_url"></image>
      </view>
  </view>
  <view class="gain_card_voucher" :style="'background:' + ((myCardVoucherDetail.shareCount-myCardVoucherDetail.shareGainCount)==0||myCardVoucherDetail.curUserGainCount>=1?'#eee':platformSetting.defaultColor)" v-else @tap="sureGainCardVoucherFun(myCardVoucherDetail.id)">
      <text v-if="myCardVoucherDetail.curUserGainCount<1">领取卡券</text>
      <text v-else-if="(myCardVoucherDetail.shareCount-myCardVoucherDetail.shareGainCount)==0">卡券已被领完</text>
      <text v-else>您已领取过了</text>
      
  </view>
  <!-- 已核销列表 -->
  <view class="verification_block_title" :style="'border-left: 4rpx solid ' + platformSetting.defaultColor" v-if="myCardVoucherDetail.verifyRecords.length!=0">
    <text class="verification_block_title_text">已核销列表</text>
  </view>
  <view class="verification_block" v-if="myCardVoucherDetail.verifyRecords.length!=0">
    <view class="verification_title">
      <view class="verification_title_item" style="width:20%">
        <text>操作人</text>
      </view>
      <view class="verification_title_item" style="width:40%">
        <text>核销内容</text>
      </view>
      <view class="verification_title_item" style="width:40%">
        <text>核销时间</text>
      </view>
    </view>
    <view class="verification_list">
      <view class="checkbox verification_item" v-for="(item, index) in myCardVoucherDetail.verifyRecords" :key="index">
        <text class="verification_item_data" style="width:20%">{{item.operatorPlatformUserName}}</text>
        <text class="verification_item_data" style="width:40%">{{item.orderProcess}}</text>
        <text class="verification_item_data" style="width:40%">{{item.processTime}}</text>
      </view>
    </view>
  </view>
  <!-- 分享 -->
  <view class="zhezhao" v-if="showTypeTwo" @tap="showShareClose"></view>
  <view class="select_share_list" :animation="animationDataTwo">
    <view class="select_share_item" v-for="(item, index) in shareTypeData" :key="index">
      <text class="select_share_name" @click.stop="showPoster" v-if="item.type=='text'">{{item.name}}</text>
      <button open-type="share" class="select_share_name" v-else>{{item.name}}</button>
    </view>
    <view class="select_share_item cancel_select_share" @click.stop="showShareClose">
      <text class="select_share_name">取消</text>
    </view>
  </view>
<posters-card-voucher-component :ewmImgUrl="ewmImgUrl" :title="myCardVoucherDetail.cardName" v-if="posterState" @closePoaster="getChilrenPoster"></posters-card-voucher-component>
</view>
</template>

<script>

export default {
  data() {
    return {
      myCardVoucherDetail: null,
      optParam: {},
      platformSetting: "",
      loginUser: "",
      ewmCode:'',
      showTypeTwo:false,
      posterState: false,
      ewmImgUrl: "",
      shareTypeData: [{
        name: '发送给朋友',
        type: 'botton'
      },{
        name: '生成海报',
        type: 'text'
      }],
      animationDataTwo: null,
    };
  },

  components: {},
  props: {},
  // option数据 用来转发和刷新
  onLoad: function (options) {
    console.log("options", options);
    this.optParam = options;
    if(getApp().globalData.loginUser){
        this.getData(options.id);
    }else{
        let url="my_card_voucher_detail.html?id="+options.id
        let backUrl=encodeURIComponent(url)
        getApp().globalData.checkIfLogin(backUrl)
    }
  },
  onReady: function () {
    this.setData({
      platformSetting: getApp().globalData.setting.platformSetting,
      loginUser: getApp().globalData.loginUser
    });
      console.log(getApp().globalData.loginUser)
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {},

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.getData(this.optParam.id);
    wx.stopPullDownRefresh();
  },
  /**
   * 用户点击右上角分享
   */
  onShareTimeline:function(){
    return this.shareFun()
  },
  onShareAppMessage: function (res) {
    console.log(res);
    return this.shareFun()
  },
  methods: {
    shareFun:function(){
        let that = this;
        that.showShareClose();
        let params = {
          id: this.optParam.id
        };
        let shareName = getApp().globalData.loginUser.platformUser.nickname+"邀请您一起瓜分【"+that.myCardVoucherDetail.cardName+"】";
        let shareAppMessageData = getApp().globalData.shareForFx2('my_card_voucher_detail', shareName, params, '', 'id');
        console.log('params:', params);
        return shareAppMessageData;
    },
    // 关闭海报
    getChilrenPoster:function(e) {
      let that = this;
      that.setData({
        posterState: false
      });
    },
    showPoster: function () {
      let that = this;
      console.log('===showPoster====', that.loginUser.id);
      that.showShareClose();
      if (that.loginUser) {
        let ewmImgUrl = getApp().globalData.getQrCode({
          type: "card_voucher",
          id: that.optParam.id
        });
        that.setData({
          posterState: true,
          ewmImgUrl: ewmImgUrl
        });
      } else {
        wx.showModal({
          title: '提示',
          content: '您还未登录，点击【确定】重新加载',
          success: function (res) {
            if (res.confirm) {
              that.getSessionUserInfo();
            } else if (res.cancel) {}
          }
        });
      }
    },
    sureGainCardVoucherFun:function(id){
        let that=this
        console.log("id",id)
        if(that.myCardVoucherDetail.shareCount-that.myCardVoucherDetail.shareGainCount==0){
            wx.showToast({
              title: "已被领取完了",
              image: '/wxcomponents/images/icons/tip.png',
              duration: 2000
            });
            return
        }else if(that.myCardVoucherDetail.curUserGainCount>=1){
            wx.showToast({
              title: "您已领取过了",
              image: '/wxcomponents/images/icons/tip.png',
              duration: 2000
            });
            return
        }else{
           wx.showModal({
             title: '提示',
             content: "您确定要领取该卡券吗！",
             success: function (res) {
               if (res.confirm) {
                 console.log('用户点击确定');
                 that.gainCardVoucherFun(id);
               } else if (res.cancel) {
                 console.log('用户点击取消');
               }
             }
           }); 
        }
    },
    gainCardVoucherFun:function(id){
        let that = this;
        let getParam = {};
        getParam.cardVoucherInstanceId = id;
        let customIndex = getApp().globalData.AddClientUrl("/wx_gain_card_voucher.html", getParam, 'get');
        wx.request({
          url: customIndex.url,
          header: getApp().globalData.header,
          success: function (res) {
            console.log("gainCardVoucherFun",res.data);
            if(res.data.errcode==0){
                wx.showToast({
                  title: "领取成功",
                  icon: 'success',
                  duration: 2000
                });
                setTimeout(function(){
                    getApp().globalData.linkEvent("my_card_voucher.html")
                },2000)
                // that.getData(res.data.relateObj.id)
            }else{
                wx.showToast({
                  title: "领取失败",
                  image: '/wxcomponents/images/icons/tip.png',
                  duration: 2000
                });
                // setTimeout(function(){
                //     getApp().globalData.toIndex()
                // },1000)
            }
            wx.hideLoading();
          },
          fail: function (res) {
            wx.hideLoading();
            getApp().globalData.loadFail();
          }
        });
    },
    showShareClose: function () {
      this.setData({
        showTypeTwo: false
      });
      let animation = wx.createAnimation({
        duration: 400,
        timingFunction: 'ease-out'
      });
      animation.height(0).step();
      let setData = animation.export();
      this.setData({
        animationDataTwo: setData
      });
    },
    showShare: function () {
      this.setData({
        showTypeTwo: !this.showTypeTwo
      });
      let showTypeTwo = this.showTypeTwo;
      let animation = wx.createAnimation({
        duration: 400,
        timingFunction: 'ease-in-out'
      });
      console.log("=======popupFormPage==========", animation, this.showType);

      if (showTypeTwo) {
        animation.height(150).step();
      } else {
        animation.height(0).step();
      }

      this.setData({
        animationDataTwo: animation.export()
      });
    },
    getData: function (id) {
      let that = this;
      let getParam = {};
      getParam.instanceId = id;
      let customIndex = getApp().globalData.AddClientUrl("/wx_get_user_card_voucher_instance_detail.html", getParam, 'get');
      wx.request({
        url: customIndex.url,
        header: getApp().globalData.header,
        success: function (res) {
          console.log(res.data);
          wx.hideLoading();
          let myCardVoucherDetail = res.data.relateObj;
          that.setData({
            myCardVoucherDetail: myCardVoucherDetail
          });
          console.log(that.myCardVoucherDetail);
          that.getVerificationCode(myCardVoucherDetail)
        },
        fail: function (res) {
          wx.hideLoading();
          getApp().globalData.loadFail();
        }
      });
    },
    getVerificationCode: function (data) {
      var that = this;
      let params={
          code:data.instanceCode,
          verifyScanType:1
      }
      var customIndex = getApp().globalData.AddClientUrl("/wx_get_scan_verify_parameter.html", params);
      wx.request({
        url: customIndex.url,
        header: getApp().globalData.header,
        success: function (res) {
          console.log("getVerificationCode", res.data);
          if (res.data.errcode == 0) {
            that.setData({
              verificationCodeData: res.data.relateObj
            });
            that.getEwmCode(res.data.relateObj);
          } else {
            wx.showModal({
              title: '错误',
              content: res.data.errMsg,
              success: function (res) {
                if (res.confirm) {
                  console.log('用户点击确定');
                  wx.navigateBack({
                    delta: 1
                  });
                } else if (res.cancel) {
                  console.log('用户点击取消');
                  wx.navigateBack({
                    delta: 1
                  });
                }
              }
            });
          }
        },
        complete: function (res) {}
      });
    },
    getEwmCode: function (data) {
      let that = this;
      let userId = "";

      if (getApp().globalData.loginUser && getApp().globalData.loginUser.platformUser) {
        userId = 'MINI_PLATFORM_USER_ID_' + getApp().globalData.loginUser.platformUser.id;
      } // + "%26verifyScanType%3d" + that.onloadOpt.verifyScanType + "%26sign%3d" + data.sign + "%26seq%3d" + data.seq + "%26scene%3d" + userId 
      let getUrl = getApp().globalData.AddClientUrl("/super_shop_manager_get_mini_code.html");
      that.setData({
        ewmCode: getUrl.url + '&path=pageTab%2findex%2findex%3fVERIFICATION_CODE%3d' + data.verifyScanCode + "%26verifyScanType%3d1%26sign%3d" + data.sign
      });
      console.log("ewmCode", that.ewmCode);
    },
    /* 组件事件集合 */
    tolinkUrl: function (e) {
      let linkUrl = e.currentTarget.dataset.link;
      getApp().globalData.linkEvent(linkUrl);
    },
    scrollTopToReflesh: function () {},
    scrollBottomToLoadMore: function () {},
    setData: function (obj) {
      let that = this;
      let keys = [];
      let val, data;
      Object.keys(obj).forEach(function (key) {
        keys = key.split('.');
        val = obj[key];
        data = that.$data;
        keys.forEach(function (key2, index) {
          if (index + 1 == keys.length) {
            that.$set(data, key2, val);
          } else {
            if (!data[key2]) {
              that.$set(data, key2, {});
            }
          }

          data = data[key2];
        });
      });
    }
  }
};
</script>
<style>
@import "./index.css";
</style>